package com.cskaoyan.controller;

import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.bean.vo.CollectionGoodsVo;
import com.cskaoyan.bean.vo.PageT;
import com.cskaoyan.bean.vo.TypeValueID;
import com.cskaoyan.domain.MarketCollect;
import com.cskaoyan.domain.MarketGoods;
import com.cskaoyan.domain.MarketUser;
import com.cskaoyan.service.CollectionService;
import com.cskaoyan.service.GoodsService;
import com.github.pagehelper.PageHelper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("wx/collect")
public class WxCollectController {
    @Autowired
    CollectionService collectionService;
    @Autowired
    GoodsService goodsService;
    @GetMapping("list")
    public BaseRespVo list(PageT pageT){
        Subject subject = SecurityUtils.getSubject();
        Integer userId=0;
        if (subject.isAuthenticated()) {
            MarketUser principal = (MarketUser) subject.getPrincipal();
            userId = principal.getId();
        }
        int type = pageT.getType();
        int page = pageT.getPage();
        int limit = pageT.getLimit();
        PageHelper.startPage(page,limit);
        List<CollectionGoodsVo> goodsList = goodsService.selectGoodCollectionListById(userId);
        CommonData data = CommonData.data(goodsList);
        return BaseRespVo.ok(data);
    }

    @PostMapping("addordelete")
    public BaseRespVo addOrDelete(@RequestBody TypeValueID typeValueID){
        Subject subject = SecurityUtils.getSubject();
        Integer userId=0;
        if (subject.isAuthenticated()) {
            MarketUser principal = (MarketUser) subject.getPrincipal();
            userId = principal.getId();
        }
        int type = typeValueID.getType();
        int valueId = typeValueID.getValueId();
        MarketCollect collect = collectionService.selectCollectionByValueId(valueId);
        MarketCollect marketCollect = new MarketCollect();
        if (collect == null){
            marketCollect.setUserId(userId);
            marketCollect.setValueId(valueId);
            marketCollect.setType((byte)type);
            marketCollect.setAddTime(LocalDateTime.now());
            marketCollect.setDeleted(false);
            collectionService.insertGoodIntoCollection(marketCollect);
        }else {
            collectionService.deleteCollectionOFGood(valueId);
        }
        return BaseRespVo.ok();
    }
}
